﻿#region Using namespaces

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using BOL.Apps.GeneNetworkBrowser.IO;
using BOL.Apps.GeneNetworkBrowser.ViewModels;

#endregion

namespace BOL.Apps.GeneNetworkBrowser.Windows
{
    /// <summary>
    /// Interaction logic for GeneValuesWindow.xaml
    /// </summary>
    public partial class GeneValuesWindow : Window
    {
        private bool _isFirstRowHeader;
        private string _delimiter;
        private string _filePath;
        private int _numberOfRows;
        private int _numberOfValues;
        //private GeneIdType _geneIDType;

        public GeneValuesWindow()
        {
            InitializeComponent();
        }

        private void Browse(object sender, RoutedEventArgs e)
        {
            if (_rbDelimiterTab.IsChecked.HasValue && _rbDelimiterTab.IsChecked.Value)
                _delimiter = "\t";
            if (_rbDelimiterComma.IsChecked.HasValue && _rbDelimiterComma.IsChecked.Value)
                _delimiter = ",";
            if (_rbDelimiterCustom.IsChecked.HasValue && _rbDelimiterCustom.IsChecked.Value)
                _delimiter = _tbDelimiterCustom.Text;

            _isFirstRowHeader = _cbFirstRowHeader.IsChecked.Value;
            //_geneIDType = _dgcbIdType.
            if (!Int32.TryParse(_tbNumberToShow.Text, out _numberOfRows))
                MessageBox.Show("Input the number of rows to preview", String.Empty, MessageBoxButton.OK, MessageBoxImage.Error);

            var ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Title = "Open a project file";
            ofd.Filter = "Text/CSV files|*.txt;*.csv|All Files|*.*";
            ofd.RestoreDirectory = true;

            StreamReader sr;
            DataTable table = new DataTable();
            DataColumn column;
            DataRow row;

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _filePath = ofd.FileName;
                sr = new StreamReader(_filePath);

                try
                {
                    switch (ofd.FilterIndex)
                    {
                        case 1: // Text/CSV file
                        default:
                            

                            char[] delimiters = _delimiter.ToCharArray();
                            string line = String.Empty;
                            string[] temp; // temporary string array splitted by delimiter

                            int i, j;

                            line = sr.ReadLine();
                            temp = line.Split(delimiters);
                            int numberOfColumns = temp.Length;
                            _numberOfValues = numberOfColumns - 1;

                            if (_isFirstRowHeader)
                            {
                                foreach (var t in temp)
                                {
                                    column = new DataColumn(t);
                                    table.Columns.Add(column);
                                }

                                _numberOfRows++;
                                line = sr.ReadLine();
                                temp = line.Split(delimiters);
                            }
                            else
                            {
                                for (j = 0; j < numberOfColumns; j++)
                                {
                                    column = new DataColumn(j.ToString());
                                    table.Columns.Add(column);
                                }
                            }

                            for (i = 0; i < _numberOfRows; i++)
                            {
                                row = table.NewRow();
                                for (j = 0; j < numberOfColumns; j++)
                                    row[j] = temp[j];
                                table.Rows.Add(row);

                                line = sr.ReadLine();
                                temp = line.Split(delimiters);
                            }

                            table.AcceptChanges();
                            _dgPreview.DataContext = table;

                            break;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, ex.Source, MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    sr.Close();
                }
            }

            _tbFileName.Text = _filePath;
        }

        private void OK(object sender, RoutedEventArgs e)
        {
            IEnumerable<Network> networks = null;

            var header = _dgPreview.Columns.Select(x => x.Header.ToString()).ToArray();
            var gvr = new GeneValueReader(_filePath, _isFirstRowHeader, _numberOfValues, _delimiter.ToCharArray());
            
            var gvrd = gvr.Read();
            gvr.Close();

            int numberOfValues = header.Length - 1;
            //if (numberOfValues != gvrd.First().Value.Length)
            //    throw new ArgumentOutOfRangeException();

            switch (_cbNetworkTarget.SelectedIndex)
            {
                case 0: // Current Network
                    //networks = new Network[1] { ((mw._documentPane.SelectedItem as BOL.Apps.GeneNetworkBrowser.Controls.NetworkDocument).DataContext as NetworkDocumentViewModel).Network };
                    break;
                case 1: // All Open Networks
                    //networks = mw._documentPane.Items.Cast<NetworkDocumentViewModel>().Select(x => x.Network);
                    break;
                case 2: // All Networks In Current Projects
                    throw new NotImplementedException();
                //break;
                case 3: // All Networks In All Open Projects
                    throw new NotImplementedException();
                //break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            foreach (var network in networks)
                foreach (var gene in network.Vertices)
                    if (gvrd.ContainsKey(gene.Id))
                    {
                        for (int i = 0; i < numberOfValues; i++)
                            gene.Attributes.Add("Cox", gvrd[gene.Id][i]);
                    }

            DialogResult = true;
        }
    }
}
